using Lemon.BackgroundJobs.Abstractions;
using Lemon.BackgroundJobs.Abstractions.PublishSubscribe;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Lemon.BackgroundJobs.RabbitMQ;

namespace Lemon.BackgroundJobs.PublishConsole;

public class PublishService : IHostedService
{
    private readonly IHostApplicationLifetime _hostApplicationLifetime;

    public PublishService(IHostApplicationLifetime hostApplicationLifetime)
    {
        _hostApplicationLifetime = hostApplicationLifetime;
    }
        
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables();

        IConfiguration configuration = builder.Build();

        var services = new ServiceCollection();
        services.AddTransient<IServiceCollection>(x => services);
        services.AddLogging();
        services.AddSingleton<IConfiguration>(configuration);
        services.UseRabbitMQ();

        services.BuildServiceProvider().GetService<IPublishSubscribe>()
            ?.Publish(new TestModel()
        {
            Id = Guid.NewGuid(),
            Name = "test"
        }, "TestJob");

        Console.WriteLine("按任意键退出");
        Console.ReadKey();
        
        _hostApplicationLifetime.StopApplication();
    }

    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}